package com.example.demo01.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;

import java.util.Locale;

@Configuration
public class MvcConfig implements WebMvcConfigurer {
    //
//    @Override
//    public void addInterceptors(InterceptorRegistry registry) {
//        MyI18nInterceptor myI18nInterceptor = new MyI18nInterceptor();
//        InterceptorRegistration registration = registry.addInterceptor(myI18nInterceptor);
//        registration.addPathPatterns("/**");
//    }

    // bean 的名字必须为 localeResolver，请求头为 Accept-Language
    // 这里选用的是 AcceptHeaderLocaleResolver()这个类，目的是使用请求头中的Accept-Language的属性进行语言切换
    // 处理逻辑在 AcceptHeaderLocaleResolver#resolveLocale 方法中

    // 在 WebMvcAutoConfiguration 中有对 AcceptHeaderLocaleResolver 的注入
    // 但是是条件注入，@ConditionalOnMissingBean(name = DispatcherServlet.LOCALE_RESOLVER_BEAN_NAME)
    // 如果不存在 localeResolver 为名字的 bean 才自动注入到容器
    /**
     *      @Override
     *      @Bean
     *      @ConditionalOnMissingBean(name = DispatcherServlet.LOCALE_RESOLVER_BEAN_NAME)
     * 		public LocaleResolver localeResolver() {
     * 			if (this.webProperties.getLocaleResolver() == WebProperties.LocaleResolver.FIXED) {
     * 				return new FixedLocaleResolver(this.webProperties.getLocale());
     *            }
     * 			AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
     * 			localeResolver.setDefaultLocale(this.webProperties.getLocale());
     * 			return localeResolver;
     *        }
     */
    @Bean
    AcceptHeaderLocaleResolver localeResolver(){
        AcceptHeaderLocaleResolver resolver = new AcceptHeaderLocaleResolver();
        resolver.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
        return resolver;
    }
}
